package huawei;

import java.util.Stack;

/**
 * 仿LISP计算
 */
public class Q134 {

    public static void main(String[] args) {
//        String orgStr = "(div 12 (sub 45 45))";
//        String orgStr = "(add 1 (div -7 3))";
        String orgStr = "(sub(mul 2 4)(div 9 3))";



        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < orgStr.length(); i++) {

            if (orgStr.charAt(i) == '(') {
                stack.push('(');
            } else if (orgStr.charAt(i) == ')') {
                StringBuilder sb = new StringBuilder();
                while (stack.peek() != '(') {
                    sb.insert(0, stack.pop());
                }
                stack.pop(); // 弹出 '('

                String[] strings = sb.toString().split(" ");
                String op = strings[0];
                Integer num1 = Integer.parseInt(strings[1]);
                Integer num2 = Integer.parseInt(strings[2]);

                int result = 0;
                if (op.equals("add")) {
                    result = num1 + num2;
                } else if (op.equals("sub")) {
                    result = num1 - num2;
                } else if (op.equals("mul")) {
                    result = num1 * num2;
                } else {
                    if (num2 != 0) {
                        result = (int) Math.floor(((double)num1) / num2);
                    } else {
                        System.out.println("error"); // error
                        return;
                    }
                }

                if (!stack.isEmpty() && stack.peek() != ' ') {
                    stack.push(' ');
                }

                String tmp = result + "";
                for (int j = 0; j < tmp.length(); j++) {
                    stack.push(tmp.charAt(j));
                }

            } else if (orgStr.charAt(i) == ' ') {
                if (stack.peek() != ' ') {
                    stack.push(' ');
                }
            } else {
                stack.push(orgStr.charAt(i));
            }
        }

        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.insert(0, stack.pop());
        }

        System.out.println(sb.toString());
    }
}
